<?php
namespace Home\Controller;
use Think\Controller;
class UsersController extends Controller {
    //判断是否登录
    public function index(){
        if(!$_SESSION['islogin']== 2){
            $this->redirect('Login');
        }else{
            $this->display();
        }
    }

    public  function login_post(){
        //处理登录
        if(SESSION('islogin')==2){
            $this -> redirect('index/index');exit;
        }
        if(isset($_POST['user_name']) && isset($_POST['user_password'])){
            $User = M('users');
            $data['user_name'] = I('user_name');
            $data['user_password'] = md5(I('post.user_password'));
            $data_key = $User -> where($data) -> find();
            if($data_key){
                //添加到本地session
                $User_Id = $User -> where($data) ->getField('user_id');
                if($User_Id ){
                    SESSION('islogin',2);
                    SESSION('user_id', $User_Id);
                    SESSION('user_name', $data['user_name']);
                }
                // $this -> success('登录成功！',U('Index/index'));
                echo R('Api/Base/ApiSuccess',array('登录成功！'));exit;

            }else{
                //$this -> error('密码错误',U('Login'),5);
                echo R('Api/Base/ApiError',array('密码错误'));;exit;
            }
        }

    }

    //退出登录
    public function outLogin(){
        session(null);
        echo R('Api/Base/ApiSuccess',array('0'));exit;
    }


    //注册
    public function regist_post(){
       if(isset($_POST['user_name']) && isset($_POST['user_password'])) {
               $User = D('users');
            if ($User->create()) {
                   $data['user_name'] =I('post.user_name');
                   $data['user_password'] = md5(I('post.user_password'));
                    if ($User->add($data)) {
                       // $e = $this->success('注册成功',U('Login'), 3);
                        echo R('Api/Base/ApiSuccess',array('注册成功'));exit;  //注册成功
                    } else {
                       // $this->error('注册失败！', U('Signup'), 3);
                        echo R('Api/Base/ApiError',array('注册失败'));exit;
                    }
        }else {
                //自动验证不过
                $msg = $User->getError();
                echo R('Api/Base/ApiError',array($msg));exit;
           }
      }
    }

}


